"""
time: 2024/10/29
title: Internet
message:
网络包请求
"""
import json
import requests


class Internet:
    def __init__(self, url_root=None):
        self.root_path = url_root

    def internet_get(self, url):
        """
        GET请求
        :param url:
        :return:
        """
        if self.root_path is not None:
            urls = self.root_path + url.strip()
        else:
            urls = url
        req = requests.get(urls, headers={'Content-Type': 'application/json'})
        return req.json()

    def internet_post(self, url, headers=None, data=None):
        """
        POST请求
        :param url:
        :param headers:
        :param data:
        :return:
        """
        if headers is None:
            headers = {'Accept': 'application/json',
                       'Content-Type': 'application/json'}
        if data is None:
            data = {}

        if self.root_path is not None:
            urls = self.root_path + url.strip()
        else:
            urls = url

        # 发送POST请求
        response = requests.post(urls, headers=headers, json=data)

        # 检查请求是否成功
        if response.status_code == 200:
            # 解析并打印响应内容
            response_data = response.json()
            return response_data
            # return json.dumps(response_data, indent=4)  # 格式化输出JSON数据
        else:
            # 打印错误信息
            print(f"请求失败，状态码：{response.status_code}，响应内容：{response.text}")
            return {}
